package problem912;

import java.util.Random;

//912.排序数组
//https://leetcode.cn/problems/sort-an-array/

//版本2

class Solution2 {
    public int[] sortArray(int[] nums) {
        quickSort(nums, 0, nums.length-1);
        return nums;
    }
    public void quickSort(int[] nums, int l, int r) {
        if(l >= r) return;

        //随机选key
        int key = nums[new Random().nextInt(r-l+1) + l];

        int left = l-1, right = r+1, i = l;
        while(i < right) {
            if(nums[i] == key) i++;
            else if(nums[i] < key) swap(nums, ++left, i++);
            else if(nums[i] > key) swap(nums, --right, i);
        }
        //[l, left] [left+1, right-1] [right, r]
        quickSort(nums, l, left);
        quickSort(nums, right, r);
    }

    public static void  swap(int[] nums, int a, int b) {
        int t = nums[a];
        nums[a] = nums[b];
        nums[b] = t;
    }
}